<script setup lang="ts">
const casinoStore = useCasinoStore()
const { casinoNav, casinoGameList, currentCasinoNav, casinoRecData, cateHotData, cateProviderData } = storeToRefs(casinoStore)
const { isLogin } = storeToRefs(useAppStore())

const { VITE_CASINO_HOME_PAGE_SIZE } = getEnv()
const searchKeyword = ref('')
const paginationConfig = reactive({
  page: 1,
  page_size: VITE_CASINO_HOME_PAGE_SIZE,
})
const params = computed(() => {
  return {
    cid: currentObject.value?.cid,
    ty: currentObject.value?.ty,
  }
})
const memberGameCateGamesParams = computed(() => {
  return {
    ...params.value,
    sort: EnumCasinoSortType.hot,
    ...paginationConfig,
  }
})
const showAll = computed(() => currentCasinoNav.value === '-1&all')
const currentObject = computed(() => {
  return casinoNav.value?.find(item => item.value === currentCasinoNav.value)
})
const isSearchMode = computed(() => searchKeyword.value.trim().length > 0)

const isProvider = computed(() => currentObject.value?.cid === '5')
const notifyThrottle = throttle(() => {
  /* openNotify({
    type: 'info',
    message: t('no_game_info_tip'),
  }) */
}, 5 * 1000, { leading: true, trailing: false })

// 搜索数据
const {
  page,
  page_size,
  total,
  list: searchGameList,
  run: runSearchCasinoGames,
  total: totalSearchGame,
  loadMore: loadMoreSearchGame,
  loading: loadingSearchGame,
} = useList(ApiMemberGameSearch, {
  onSuccess(res, params) {
    /* if (res.d && res.d.length > 0) {
      const word = params[0].w

      // 去重
      if (keywordLive.value.includes(word))
        keywordLive.value.splice(keywordLive.value.findIndex(t => t === word), 1)

      keywordLive.value.unshift(word)
      keywordLive.value = keywordLive.value.slice(0, 5)
      Local.set(STORAGE_SEARCH_KEYWORDS_LIVE, keywordLive.value)
    } */
  },
  onAfter() {
    //setInputingFalse()
  },
}, { page_size: 15 })

// 当前选中分类数据
const {
  data,
  runAsync,
  loading,
} = useRequest(ApiMemberGameCate, {
  onSuccess: (res) => {
    console.log('res ============+++++++++++++ ', res)
    judgeGameEmpty(res)
  },
})



// 加载更多
const {
  data: moreList,
  runAsync: runMoreMemberGameCateGames,
  loading: moreLoading,
} = useRequest(ApiMemberGameCateGames)

const providerList = computed(() => {
  if (data.value && data.value.venue && !!data.value.venue.pc)
    return data.value.venue.pc[0]

  return []
})
const listTotal = computed(() => {
  return data.value ? data.value.total : 0
})
// 单行数据
const list = computed(() => {
  if (!(data.value && data.value.games && data.value.games.length))
    return []

  const renderList: any = data.value.games

  if (moreList.value?.d && moreList.value.d.length)
    renderList.push(...moreList.value.d)

  return renderList
})
// 多行数据
const litems = computed(() => {
  if (data.value && data.value.litems) {
    return data.value.litems.map((a) => {
      return {
        ...a,
        path: `/category?cid=${a.cid}&ty=${a.ty ?? currentObject.value?.ty}`, // props.ty
      }
    })
  }
  return []
})
function judgeGameEmpty(res: any) {
  if (currentObject.value?.cid !== '5' && (!searchKeyword.value || !searchKeyword.value.length)) {
    if (res.litems && res.litems.length) {
      if (res.litems.filter((rr: any) => rr.nav_games && rr.nav_games.length).length === 0)
        notifyThrottle()
    }
    else {
      if (res.games && res.games.length)
        console.log('mm')
      else
        notifyThrottle()
    }
  }
}
function onSearch(w: string) {
  runSearchCasinoGames({ w })
}
function onPage(p: number) {
  page.value = p
}
function getNextData() {
  paginationConfig.page++
  runMoreMemberGameCateGames(getTy({ ...memberGameCateGamesParams.value }))
}
watch(params, () => {
  runAsync(getTy(params.value))
})

const mytab = ref<'1' | '2'>('1') // 1继续玩，2我的最爱
const { list: favList, runAsync: runAsyncFav } = useList(
  ApiMemberFavList,
  {},
  { page_size: 100 },
)
const { data: recentList, runAsync: runAsyncRecent } = useRequest(ApiMemberGameListHistory)

const useSuggest = computed(() => {
  const current = [favList.value, recentList.value][Number(mytab.value) - 1]
  return !(current && current.length > 0)
})
const suggestData = computed(() => {
  const suppierInfo = cateProviderData?.value.venue ?? { h5: [], pc: [] }
  return cateHotData.value ? cateHotData?.value.games : flatten(suppierInfo.h5)
})
const currentFavData = computed(() => {
  const current = [favList.value, recentList.value][Number(mytab.value) - 1]
  return useSuggest.value ? suggestData.value : current
})

watch([isLogin], ([val]) => {
  if (val) {
    application.allSettled([runAsyncFav(), runAsyncRecent()])
  }
}, { immediate: true })

</script>
<template>
  <div class="px-[.875rem]">
    <div class="-mt-[var(--safe-header)]">
      <div class="banner-bg relative -mx-[.875rem] -mt-4 pt-[var(--safe-header)] sm:mx-0 sm:mt-0 sm:pt-0">
        <AppBanner />
      </div>

      <div class="-mx-[.875rem] bg-layer2 px-[.875rem] min-h-screen">
        <div class="relative  mb-4">
          <AppGameSearch @search="onSearch" v-model="searchKeyword" />
        </div>
        <BaseTabs v-if="!isSearchMode" ref="tebRef" v-show="casinoNav && casinoNav.length > 0"
          v-model="currentCasinoNav" :list="casinoNav ?? []" :center="false" size="large" />
        <template v-if="isSearchMode">
          <BaseGameList @page="onPage" :loading="loadingSearchGame" :data="searchGameList" :total="total" :page="page"
            :page-size="page_size" />
        </template>
        <template v-else>
          <template v-if="showAll">
            <div v-if="isLogin" class="text-white">
              <!-- 继续玩，我的最爱 -->
              <AppSlideMulti :path="mytab === '1' ? '/recent' : '/favorite'"
                :cid="(useSuggest && !cateHotData) ? '5' : ''" :data="currentFavData" use-cloud-img>
                <template #title>
                  <div class="flex items-center">
                    <BaseButton @click="mytab = '1'"
                      class="  flex-1 px-2 py-1 text-xs center h-auto whitespace-nowrap rounded-none border-b-2 "
                      :class="[mytab === '1' ? '!font-bold  border-b-success' : '!font-normal border-b-transparent']"
                      type="none">{{ $t('goon_play') }}</BaseButton>
                    <BaseButton @click="mytab = '2'"
                      class="flex-1 px-2 py-1 text-xs center h-auto whitespace-nowrap rounded-none border-b-2 "
                      :class="[mytab === '2' ? '!font-bold  border-b-success' : '!font-normal border-b-transparent']"
                      type="none">{{ $t('my_fav') }}</BaseButton>
                  </div>
                </template>
              </AppSlideMulti>
            </div>
            <div class="text-white" v-for="item in casinoGameList" :key="item.name">
              <AppSlideMulti v-if="item.nav_games && item.nav_games.length > 0" :total="item.total" 
                :title="item.name" :data="item.nav_games" :cid="item.cid" :ty="item.ty" :pid="item.platform_id"
                :path="item.path" use-cloud-img />
            </div>
          </template>
          <template v-else-if="currentObject">
            <BaseGameList @more="getNextData" :loading="loading" :more-loading="moreLoading" :data="list"
              :total="listTotal" :page-size="paginationConfig.page_size" mode="more" />
          </template>

        </template>
      </div>

    </div>
    <div class="page-bg" style="animation-delay: -0.235294s;">
    </div>
  </div>
</template>
<style scoped lang="scss">
.banner-bg {
  background-image: linear-gradient(to bottom, transparent, rgb(35, 38, 38) 20rem);
}

.page-bg {
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  z-index: -1;
  height: 60vh;
}

.page-bg {
  //animation: bgTransition 1s forwards paused;
}

@keyframes bgTransition {
  0% {
    background-color: rgb(101, 84, 48);
  }

  6% {
    background-color: rgb(129, 58, 36);
  }

  12% {
    background-color: rgb(66, 78, 151);
  }

  18% {
    background-color: rgb(127, 21, 170);
  }

  24% {
    background-color: rgb(149, 92, 51);
  }

  29% {
    background-color: rgb(127, 21, 170);
  }

  35% {
    background-color: rgb(127, 96, 156);
  }

  41% {
    background-color: rgb(127, 21, 170);
  }

  47% {
    background-color: rgb(127, 21, 170);
  }

  53% {
    background-color: rgb(23, 62, 171);
  }

  59% {
    background-color: rgb(127, 21, 170);
  }

  65% {
    background-color: rgb(57, 70, 148);
  }

  71% {
    background-color: rgb(64, 111, 40);
  }

  76% {
    background-color: rgb(107, 72, 156);
  }

  82% {
    background-color: rgb(23, 62, 171);
  }

  88% {
    background-color: rgb(163, 45, 35);
  }

  94% {
    background-color: rgb(149, 97, 46);
  }

  100% {
    background-color: rgb(101, 84, 48);
  }
}
</style>